const express = require('express');
const app = express();
const bodyParser = require('body-parser');
// const socketIO  = require("socket.io");
const utils = require('./core/utils');
const AI = require('./AI/IndexAnalysis');
// var expressWs = require('express-ws');


const urlencodedParser = bodyParser.json();
const biz = require('./biz/index');
const router = express.Router();
const API = require('./api/index');
const DB = require('./db/index');

// DB.AlarmContactGroupUser.findByAlarmContactGroupId({alarm_contact_group_id:1}).then(res=>{
// 	console.log('findByAlarmContactGroupId==========>',res);
// })


// 定义局部变量
let ioUser = {}; // socket连接的用户
let __socket = null;

app.use(express.static(__dirname + '/public'));
// expressWs(router);
API.init(router,urlencodedParser);

router.post('/device/event', urlencodedParser, function (req, res) {
	let param = typeof req.body == 'string' ? JSON.parse(req.body) : req.body;
	let socketId = ioUser[param.id];
	console.log(socketId,param);
	// todo 处理入库的逻辑业务
	if(__socket && socketId){
		__socket.to(socketId).emit('server_to_device',{code:0,msg:param.data});
		console.log('ai向客户端'+param.id+'推送数据'+JSON.stringify({code:0,msg:param.data})+',socketId='+socketId)
		res.send({code:0});
	}else{
		res.send({code:-1});
	}
});

// router.ws('/connect', function (ws, req){
// 	ws.on('message', function (msg) {
//
// 	})
// });

var WebSocketServer = require('ws').Server,
	wss = new WebSocketServer({ port: 8181 });
wss.on('connection', function (ws) {
	console.log('client connected');
	ws.on('message', function (message) {
		console.log(message);
	});
});

function socketInit(server){
	return false;
	// let io = socketIO(server,{
	// 	cors: {
	// 		origin: "*",
	// 		methods: ["GET", "POST"]
	// 	}
	// });
	// io.sockets.on('connection', (socket) => {
	// 	__socket = socket;
	// 	let userid = socket.handshake.query.id;
	// 	let source = socket.handshake.query.source;
	// 	console.log('log input param : ' + userid,source);
	// 	// 用户连接时根据参数识别用户身份
	// 	if(userid && userid != 'undefined'){
	// 		if(source == 'normal'){
	// 			ioUser[userid] = socket.id;
	// 		}else{
	// 			ioUser.ai = socket.id;
	// 		}
	// 	}else{
	// 		// 不存在 userid，则是非法用户，直接断开
	// 	}
	//
	// 	// ai算法服务器发送指标数据到业务服务器
	// 	socket.on('AISendIndexToBizServer',(msg)=>{
	// 		console.log('AISendIndexToBizServer======>',msg);
	// 		// AI.analysisIndex(msg);
	// 	});
	//
	// 	socket.on('device_to_server', (msg) => {
	// 		let d = utils.parseJson(msg);
	// 		ioUser[d.id] = socket.id;
	// 		console.log('socket.id==>',socket.id);
	// 		if(ioUser.ai){
	// 			socket.to(ioUser.ai).emit('server_to_aiDevice',{code:0,data:{id:d.id}});
	// 			console.log(msg,'发送消息到 server_to_aiDevice');
	// 		}else{
	// 			console.log('aiDevice不存在，发送消息失败');
	// 		}
	// 		console.log(msg + "普通设备连入");
	// 	});
	// 	socket.on('aiDevice_to_server',(msg)=>{
	// 		let d = utils.parseJson(msg);
	// 		// 如果是报警信息  入库
	// 		// 判断 链接是否存在
	// 		ioUser[d.id] && socket.to(ioUser[d.id]).emit('server_to_device',{code:0,msg:d.data});
	// 		// socket.emit('server_to_aiDevice',{code:0,data:{x:1,y:2}});
	// 		console.log(msg + "ai分析设备连入");
	// 	});
	// 	// socket 离线了
	// 	socket.on('disconnect', function(){
	// 		for(let name in ioUser){
	// 			if(ioUser[name] == socket.id){
	// 				delete ioUser[name];
	// 			}
	// 		}
	// 		console.log('user ' + socket.id + ' disconnected');
	// 	});
	// });
}

module.exports = {
	router:router,
	socket:socketInit
};
